package com.heima.wemedia.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.UUID;

/**
 * @作者 itcast
 * @创建日期 2021/4/13 16:12
 **/
@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Value("${file.oss.web-site}")
    String webSite;
    @Value("${file.oss.profix}")
    String profix;
    @Autowired
    FileStorageService fileStorageService;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 1. 参数校验
        if(multipartFile == null || multipartFile.getSize() == 0){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"请上传正确的素材");
        }
        // 2. 获取当前登录用户(userId)
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser == null || wmUser.getId()==null){
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH,"请先登录，在上传素材");
        }
        // 3. 上传文件到OSS中
        try {
            // 设置文件名称
            String fileName = UUID.randomUUID().toString().replaceAll("-", "");
            // 截取原文件 后缀名
            String oriName = multipartFile.getOriginalFilename();
            String suffix = oriName.substring(oriName.lastIndexOf("."));//  123124.jpg
            // 文件 在 OSS中的 名称
            String fileId = fileStorageService.store(profix, fileName + suffix, multipartFile.getInputStream());
            // 4. 创建素材信息，并保存
            WmMaterial material = new WmMaterial();
            material.setUserId(wmUser.getId());
            material.setUrl(fileId);
            material.setType((short)0); // 图片
            material.setIsCollection((short)0);
            material.setCreatedTime(new Date());
            save(material);// 保存素材信息
            material.setUrl(webSite+fileId);
            // 5. 返回结果
            return ResponseResult.okResult(material);
        }catch (Exception e){
            log.error("上传图片出现异常  ==> {}",e);
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,"上传图片出现异常");
        }
    }
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        // 1. 检查参数
        dto.checkParam();
        // 2. 判断是否登录
        Integer userId = WmThreadLocalUtils.getUser().getId();
        // 3. 查询数据
        // 3.1 分页条件
        Page<WmMaterial> pageReq = new Page(dto.getPage(), dto.getSize());
        // 3.2 查询条件
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.<WmMaterial>lambdaQuery();
        if(dto.getIsCollection()!=null && dto.getIsCollection().intValue() == 1){
            queryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        queryWrapper.eq(WmMaterial::getUserId,userId);
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        // 3.3 执行查询
        IPage<WmMaterial> pageResult = page(pageReq, queryWrapper);
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageResult.getTotal());
        // 为图片路径添加访问前缀
        List<WmMaterial> records = pageResult.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite + record.getUrl());
        }
        pageResponseResult.setData(records);
        return pageResponseResult;
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult delPicture(Integer id) {
        // 1. 检查参数
        if(id == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 根据素材ID + 登录用户ID   查询素材信息
        WmUser user = WmThreadLocalUtils.getUser();
        if(user == null || user.getId() == null){
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        WmMaterial material = getOne(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getId, id).eq(WmMaterial::getUserId, user.getId()));
        if(material == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 3. 根据素材ID查询关联表中是否有引用  如果有:不能删除
        Integer relCount = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if(relCount > 0){
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST,"该素材已经被引用，无法删除");
        }
        // 4. 删除素材  删除OSS中对应的素材
        removeById(id);
        fileStorageService.delete(material.getUrl());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        // 检查参数  type = 0 = 1
        if(id == null ){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 登录用户ID
        WmUser user = WmThreadLocalUtils.getUser();
        if(user == null || user.getId() == null){
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        // 修改操作
        update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection, type)
                .eq(WmMaterial::getId, id)
                .eq(WmMaterial::getUserId, user.getId()));
        return ResponseResult.okResult();
    }
}
